/<template>
  <div class="shopCar">
    <h1>购物车</h1>
    <div class="car_list">
      <div v-for="item in list" :key="item.id">
        <div v-for="value in item.children" :key="value.id">
          <div v-if="value.num" class="item">
            <input type="checkbox" v-model="value.isCheck" />
            <img :src="value.img" alt="" />
            <div>
              <h3>{{ value.title }}</h3>
              <div>
                <b>￥{{ value.price }}元</b>
                <div>
                  <button @click="reduce(value.id)">-</button>
                  <span>{{ value.num }}</span>
                  <button @click="add(value.id)">+</button>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <div class="car_foot">
      <b><input type="checkbox" v-model="allcheck" @click="checkAll" />全选</b>
      <b>总价：{{ totalPrice }}元</b>
      <b>结算：{{ totalNum }}件</b>
    </div>
  </div>
</template>

<script>
import { mapState, mapActions, mapMutations } from "vuex";
export default {
  data() {
    return {
      allcheck: false,
      totalPrice: 0,
      totalNum: 0,
    };
  },
  // 监听数据
  watch: {
    // 监听list数据
    list: {
      deep: true,
      handler(newValue) {
        const numList = [];
        newValue.forEach((item) => {
          item.children.forEach((v) => {
            if (v.num) {
              numList.push(v);
            }
          });
        });
        // 选中的数据
        const checkList = [];
        newValue.forEach((item) => {
          item.children.forEach((v) => {
            if (v.isCheck) {
              checkList.push(v);
            }
          });
        });
        this.allcheck = numList.length == checkList.length;
        this.totalPrice = 0;
        this.totalNum = 0;
        // 对选中的数据进行遍历
        checkList.forEach((item) => {
          this.totalPrice += item.price * item.num;
          this.totalNum += item.num;
        });
      },
    },
  },
  // 计量属性
  computed: {
    ...mapState(["list"]),
  },
  methods: {
    ...mapActions(["getlist"]),
    ...mapMutations(["reduceNum", "addNum", "checkFn"]),
    add(id) {
      this.addNum(id);
    },
    reduce(id) {
      this.reduceNum(id);
    },
    checkAll() {
      this.checkFn(this.allcheck);
    },
  },
  mounted() {
    // ...mapActions([])
    this.getlist();
  },
};
</script>

<style lang='scss'>
.shopCar {
  width: 100%;
  height: 100%;
  .car_list {
    width: 100%;
    .item {
      width: 100%;
      height: 150px;
      display: flex;
      align-items: center;
      padding: 10px;
      img {
        width: 80px;
        height: 80px;
        margin: 0 10px;
      }
      button {
        width: 30px;
        height: 30px;
        span {
          padding: 0 10px;
        }
      }
    }
  }
}
</style>